<template>
  <div class="app-container">
    <div class="search-container">
      <el-form ref="queryFormRef" :inline="true" :model="queryParams">
        <el-form-item label="关键字" prop="keywords">
          <el-input
            v-model="queryParams.keywords"
            placeholder="考试名称"
            @keyup.enter="handleQuery"
          />
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-select
            v-model="queryParams.status"
            class="!w-[100px]"
            clearable
            placeholder="全部"
          >
            <el-option :value="1" label="正常" />
            <el-option :value="2" label="暂停" />
            <el-option :value="3" label="结束" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button class="filter-item" type="primary" @click="handleQuery">
            <i-ep-search />
            搜索
          </el-button>
          <el-button @click="handleResetQuery">
            <i-ep-refresh />
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card class="table-container" shadow="never">
      <template #header>
        <el-button
          v-hasPerm="['active:active:add']"
          type="success"
          @click="handleOpenDialog(undefined)"
        >
          <i-ep-plus />
          新增
        </el-button>
        <el-button
          v-hasPerm="['active:active:delete']"
          :disabled="ids.length === 0"
          type="danger"
          @click="handleDelete()"
        >
          <i-ep-delete />
          删除
        </el-button>
      </template>

      <el-table
        v-loading="loading"
        :data="ActiveList"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        default-expand-all
        row-key="id"
        @selection-change="handleSelectionChange"
      >
        <!--        <el-table-column type="selection" width="55" align="center" />-->
        <el-table-column
          label="考试名称"
          max-width="300"
          min-width="240"
          prop="name"
          show-overflow-tooltip
        />
        <el-table-column
          label="考试编码"
          max-width="120"
          min-width="120"
          prop="code"
          show-overflow-tooltip
        />
        <el-table-column
          label="报名开始时间"
          min-width="180"
          prop="apply_start"
        >
          <template #default="scope">
            {{ scope.row.apply_start.slice(0, 10) }}
          </template>
        </el-table-column>
        <el-table-column label="报名结束时间" min-width="180" prop="apply_end">
          <template #default="scope">
            {{ scope.row.apply_end.slice(0, 10) }}
          </template>
        </el-table-column>
        <el-table-column label="考试开始时间" min-width="180" prop="start_time">
          <template #default="scope">
            {{ scope.row.start_time.slice(0, 10) }}
          </template>
        </el-table-column>
        <el-table-column label="考试结束时间" min-width="180" prop="end_time">
          <template #default="scope">
            {{ scope.row.end_time.slice(0, 10) }}
          </template>
        </el-table-column>
        <el-table-column label="创建时间" min-width="180" prop="createTime" />
        <el-table-column label="状态" min-width="100" prop="status">
          <template #default="scope">
            <el-tag v-if="scope.row.status == 1" type="success">正常</el-tag>
            <el-tag v-else-if="scope.row.status == 2" type="error">暂停</el-tag>
            <el-tag v-else type="info">结束</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          fixed="right"
          label="执考考官"
          width="160"
        >
          <template #default="scope">
            <template v-for="(item, index) in scope.row.examiner" :key="index">
              <span>{{ index == 0 ? "" : " / " }}{{ item.name }}</span>
            </template>
          </template>
        </el-table-column>
        <el-table-column align="center" fixed="right" label="操作" width="200">
          <template #default="scope">
            <el-button
              v-hasPerm="['active:active:edit']"
              link
              size="small"
              type="primary"
              @click.stop="handleOpenDialog(scope.row.id)"
            >
              <i-ep-edit />
              编辑
            </el-button>
            <el-button
              v-hasPerm="['active:active:edit']"
              link
              size="small"
              type="primary"
              @click.stop="handleOpenShareDialog(scope.row)"
            >
              <i-ep-share />
              分享
            </el-button>
            <el-button
              v-hasPerm="['exam:exam:download']"
              link
              size="small"
              type="primary"
              @click.stop="downloadVideo(scope.row)"
            >
              <i-ep-download />
              下载
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-if="total > 0"
        v-model:limit="queryParams.pageSize"
        v-model:page="queryParams.pageNum"
        v-model:total="total"
        @pagination="handleQuery"
      />
    </el-card>

    <el-dialog
      v-model="dialog.visible"
      :destroy-on-close="true"
      :fullscreen="true"
      :title="dialog.title"
      size="500px"
      style="
        width: 30vw;
        min-width: 620px;
        height: 70vh;
        margin-top: 10vh;
        overflow: auto;
      "
      @closed="handleCloseDialog"
    >
      <el-form
        ref="activeFormRef"
        :model="formData"
        :rules="rules"
        label-position="top"
        label-width="80px"
        style="padding: 0 24px"
      >
        <!--        考级编码-->
        <el-form-item label="考场编码" prop="code">
          <el-input
            v-model="formData.code"
            placeholder="请输入考级系统id"
            type="number"
          />
        </el-form-item>
        <!--        考级编码 end-->
        <!--        所属代理/考试名称-->
        <el-form-item label="考试类型" prop="type">
          <template #label>
            <span>考试类型</span>
          </template>
          <el-select v-model="formData.type">
            <el-option :value="1" label="朗诵" />
            <el-option :value="2" label="主持" />
          </el-select>
        </el-form-item>
        <el-form-item label="考试名称" prop="name">
          <el-input
            v-model="formData.name"
            maxlength="20"
            placeholder="请输入考试名称"
          />
        </el-form-item>
        <!--        所属代理/考试名称 end-->
        <!--        报名开始时间-/报名结束时间-->
        <el-form-item label="报名开始时间" prop="apply_start">
          <el-date-picker
            v-model="formData.apply_start"
            :disabled-date="disabledDate"
            placeholder="请选择报名开始时间"
            type="date"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="报名结束时间" prop="apply_end">
          <el-date-picker
            v-model="formData.apply_end"
            :disabled-date="disabledDate"
            placeholder="请选择报名结束时间"
            type="date"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <!--        报名开始时间-/报名结束时间 end-->
        <!--        考试开始时间-/考试结束时间-->
        <el-form-item label="考试开始时间" prop="start_time">
          <el-date-picker
            v-model="formData.start_time"
            :disabled-date="disabledDate"
            placeholder="请选择考试开始时间"
            type="date"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="考试结束时间" prop="end_time">
          <el-date-picker
            v-model="formData.end_time"
            :disabled-date="disabledDate"
            placeholder="请选择考试结束时间"
            type="date"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <!--        考试开始时间-/考试结束时间 end-->
        <!--        选择考官-->
        <el-form-item label="执考考官" prop="examiner">
          <el-select v-model="formData.examiner" multiple>
            <el-option
              v-for="(item, index) in ExaminerOptions"
              :label="item['label'] + '-' + item['phone']"
              :value="item['value']"
              :key="index"
            />
          </el-select>
        </el-form-item>
        <!--        选择考官 end-->
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="handleCloseDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog
      v-model="shareDialog.visible"
      :destroy-on-close="true"
      :fullscreen="true"
      :title="shareDialog.title"
      size="400px"
      style="
        width: 30vw;
        min-width: 620px;
        height: 40vh;
        margin-top: 25vh;
        overflow: auto;
      "
      @closed="handleCloseShareDialog"
    >
      <el-row
        v-if="
          shareDialog.data['examinee_share_img'] &&
          shareDialog.data['examiner_share_img']
        "
      >
        <el-col :span="12">
          <div style="width: 100%; text-align: center">
            <img
              :src="shareDialog.data['examinee_share_img']"
              style="width: 80%"
            />
            <div style="width: 100%; text-align: center">考生入口</div>
          </div>
        </el-col>
        <el-col :span="12">
          <div style="width: 100%; text-align: center">
            <img
              :src="shareDialog.data['examiner_share_img']"
              style="width: 80%"
            />
            <div style="width: 100%; text-align: center">考官入口</div>
          </div>
        </el-col>
      </el-row>
      <div
        v-else
        style="
          position: absolute;
          bottom: 20px;
          left: 50%;
          transform: translateX(-50%);
        "
      >
        <el-button type="primary" @click="createQRCode">生成</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import ActiveAPI, { ActiveForm, ActiveQuery, ActiveVO } from "@/api/active";
import ExaminerAPI from "@/api/examiner";
import { useRouter } from "vue-router";

defineOptions({
  name: "Active",
  inheritAttrs: false,
});

const router = useRouter();

//  定义时间选择器只能从明天开始选择
const disabledDate = (time) => {
  const today = new Date();
  today.setHours(0, 0, 0, 0); // 将今天的时间设置为00:00:00
  return time.getTime() < today.getTime(); // 返回true表示禁用今天的日期以及之前的日期
};

const agentOptions = ref([]);
const ExaminerOptions = ref([]);
const queryFormRef = ref(ElForm);
const activeFormRef = ref(ElForm);
const loading = ref(false);
const ids = ref<number[]>([]);
const dialog = reactive({
  title: "",
  visible: false,
});
const shareDialog = reactive({
  title: "分享信息",
  data: {},
  visible: false,
});
const total = ref(0);
const queryParams = reactive<ActiveQuery>({
  pageNum: 1,
  pageSize: 10,
});
const ActiveList = ref<ActiveVO[]>();
const timeFormat = ref("HH:mm");
const formData = reactive<ActiveForm>({
  id: undefined,
  type: 1,
  status: 1,
});
const rules = reactive({
  code: [
    {
      required: true,
      message: "请输入考场编码",
      trigger: "blur",
    },
  ],
  examiner: [
    {
      required: true,
      message: "请选择执考考官",
      trigger: "blur",
    },
  ],
  type: [
    {
      required: true,
      message: "请选择考试类型",
      trigger: "blur",
    },
  ],
  name: [
    {
      required: true,
      message: "考试名称不能为空",
      trigger: "blur",
    },
  ],
  apply_start: [
    {
      required: true,
      message: "请选择报名开始时间",
      trigger: "blur",
    },
  ],
  apply_end: [
    {
      required: true,
      message: "请选择报名结束时间",
      trigger: "blur",
    },
  ],
  start_time: [
    {
      required: true,
      message: "请选择考试开始时间",
      trigger: "blur",
    },
  ],
  end_time: [
    {
      required: true,
      message: "请选择考试结束时间",
      trigger: "blur",
    },
  ],
});

/** 查询考试 */
function handleQuery() {
  loading.value = true;
  ActiveAPI.getList(queryParams).then((data) => {
    ActiveList.value = data["list"];
    total.value = data["total"];
    loading.value = false;
  });
}

/** 重置查询 */
function handleResetQuery() {
  queryFormRef.value.resetFields();
  handleQuery();
}

/**
 * 打开考试弹窗
 *
 * @param id 考试ID
 */
async function handleOpenDialog(id: number) {
  dialog.visible = true;
  if (id) {
    dialog.title = "修改考试";
    ActiveAPI.getFormData(id).then((data) => {
      Object.assign(formData, data);
      formData.examiner = JSON.parse(formData.examiner);
    });
  } else {
    dialog.title = "新增考试";
  }
}

/** 提交考试表单 */
function handleSubmit() {
  activeFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      const ActiveId = formData.id;
      if (ActiveId) {
        ActiveAPI.update(ActiveId, formData)
          .then(() => {
            ElMessage.success("修改成功");
            handleCloseDialog();
            handleQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        ActiveAPI.add(formData)
          .then(() => {
            ElMessage.success("新增成功");
            handleCloseDialog();
            handleQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}

/** 关闭弹窗 */
function handleCloseDialog() {
  dialog.visible = false;

  activeFormRef.value.resetFields();
  activeFormRef.value.clearValidate();

  formData.id = undefined;

  formData.status = 1;
}

function handleOpenShareDialog(data) {
  console.log(data);
  shareDialog.visible = true;
  shareDialog.data = { ...data };
}

function handleCloseShareDialog() {
  shareDialog.visible = false;
  shareDialog.data = {};
}

function createQRCode() {
  ActiveAPI.createQRCode(shareDialog.data.id).then((data) => {
    handleQuery();
    shareDialog.data["examiner_share_img"] = data["examiner_share_img"];
    shareDialog.data["examinee_share_img"] = data["examinee_share_img"];
  });
}

async function getOptions() {
  ExaminerOptions.value = await ExaminerAPI.getOptions();
}

function downloadVideo(data: any) {
  ActiveAPI.getFiles(data["id"]).then((res: any) => {
    console.log(res);
    let videoUrl: string = res.url;
    const download = data.name + "考试视频.mp4"; // 指定下载文件名
    fetch(videoUrl)
      .then((response) => response.blob())
      .then((blob) => {
        // 创建一个指向blob对象的URL
        const url = window.URL.createObjectURL(blob);
        // 创建下载链接
        const link = document.createElement("a");
        link.href = url;
        link.download = download; // 指定下载文件名
        document.body.appendChild(link);
        link.click(); // 触发下载
        document.body.removeChild(link); // 清除临时创建的链接
        window.URL.revokeObjectURL(url); // 释放blob对象URL
      })
      .catch((error) => console.error("下载视频失败:", error));
  });
}

onMounted?.(() => {
  handleQuery();
  getOptions();
});
</script>
